//
//  AddAddressView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/7.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class AddAddressView: BaseView, UITableViewDataSource, UITableViewDelegate{
    var viewModel:AddAddressViewModel?
    var addressText:BaseTextField?
    var remarkText:BaseTextField?
    
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.grouped)
    lazy var selectBtn:UIButton = {
        let btn =  CommonBtn.creatSelectBtnWithTitle(title: kText("确定"), y: 50, view: self, sel:  #selector(selectBtnAction))
        return btn
    }()
    lazy var footView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 100))
        return view
    }()
    
    
    override func setUpUI() -> Void {
        super.setUpUI()
        viewModel = dataSource as? AddAddressViewModel
        
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.themeBackground = ThemeManager.ThemeColorKeys.background
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalToSuperview()
        }
        tableView.tableFooterView = footView
        footView.addSubview(selectBtn)
        
        selectBtn.isEnabled = false
        CommonBtn.createImageWithColor(color: UIColor(hexStr: "#bec3d4"), btn: selectBtn, state: UIControlState.normal)
        
        
    }
    //MARK tableViewDelegate
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identy = "identyCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? WritePasteTableViewCell
        if cell == nil {
            cell = WritePasteTableViewCell(style: .default, reuseIdentifier: identy)
            cell?.addressBtn.isHidden = true
            if indexPath.section == 0 {
                cell?.titleLabel.text = kText("地址")
                addressText = cell?.textField
                cell?.delegate = self
            }else {
                cell?.textField.placeholder = kText("请输入地址名称")
                cell?.titleLabel.text = kText("备注")
                cell?.sLine?.isHidden = true
                cell?.qrBtn.isHidden = true
                remarkText = cell?.textField
            }
            cell?.textField.delegate = self
            cell?.textField.addTarget(self, action: #selector(textFieldDidChangeValue(textField:)), for:UIControlEvents.editingChanged)
            cell?.textField.snp.updateConstraints({ (make) in
                make.right.equalToSuperview().offset(-60)
            })
            cell?.selectionStyle = .none
        }
        if indexPath.section == 0 {
            cell?.textField.text = self.viewModel?.address
        }else {
            cell?.textField.text = self.viewModel?.remark
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 35))
        view.backgroundColor = UIColor.clear
        return view
    }
    
    @objc func selectBtnAction() {
        self.endEditing(true)
        if let remake = viewModel?.remark, remake.count > 255 {
            CYMBShow.showMessage("备注文本长度超过输入限制长度")
            return
        }
        if !AppSecurityInfo.default.model.isOpenGoogle && !AppSecurityInfo.default.model.isMobileBind {
            Alert.default.show(title: "", message: kText("请先完成手机认证或谷歌认证"), actions: [kText("确认")]) {
                
            }
            Alert.default.delegate = self
            return
        }
        
        viewModel?.checkCoinAddress(returnVale: { (canAdd) in
            if canAdd {
            AppSecurityInfo.default.codeType = 10
            if AppSecurityInfo.default.model.isOpenGoogle {
                GooglePassWordManager.creatGoolPassWord(dataSource:self,style:.googlePassWordStyle,validate:.googleStyle)
            }else {
                GooglePassWordManager.creatGoolPassWord(dataSource:self,style:.googlePassWordStyle,validate:.telStyle)
            }
          }
        })
        
        
        
    }
    
    func changeStates()  {
        
        if viewModel?.address.ch_length != 0 && viewModel?.remark.ch_length != 0
           {
            selectBtn.isEnabled = true
            CommonBtn.createImageWithColor(color:kThemeColor, btn: selectBtn, state: UIControlState.normal)
        }else {
            selectBtn.isEnabled = false
            CommonBtn.createImageWithColor(color: kDisableColor, btn: selectBtn, state: UIControlState.normal)
        }
        
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension AddAddressView:OpenQrDelegate, UITextFieldDelegate {
    func openQr() {
        let c =  QRCodeViewController()
        c.completion = {[unowned self](result)in
            self.viewModel?.address = result
            self.tableView.reloadData()
            self.changeStates()
        }
        self.viewModel?.controller?.present(c, animated: true, completion: nil)
    }
    
   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
                   replacementString string: String) -> Bool {
        if textField.isEqual(addressText) {
            return true
        }
        
        return true
    }
    
    @objc func textFieldDidChangeValue(textField:UITextField) {
        if textField.isEqual(addressText) {
            viewModel?.address = textField.text!
        }else {
            viewModel?.remark = textField.text!
        }
        self.changeStates()
    }
    
}
extension AddAddressView: GoolPassWordDelegate, AlertDelegate{
    func googleVerificationt(passWord: String) {
        viewModel?.codeNumber = passWord
        self.viewModel?.addAddress()
    }
    
    
    func alert(didSelected title: String?) {
        self.viewModel?.controller?.navigationController?.pushViewController(SecurityCenterViewController(), animated: true)
    }
}
